//
//  ViewController.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//

#import "ViewController.h"
#import "NewHomeViewController.h"
#import "OnlineEducationViewController.h"
#import "BibleViewController.h"
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/UIView+ZFFrame.h>
#import <ZFPlayer/ZFPlayerConst.h>
#import "HSVideoPlayViewController.h"
#import "FKBaseNavVC.h"

@interface ViewController ()<UITabBarControllerDelegate>

@property (nonatomic, strong)ObjectAFNetWorking* objectAFN;
@property (nonatomic, strong)NSDictionary*       dic;
@property (nonatomic, strong)UIView*             centView;
@property (nonatomic, strong)NSMutableArray*     SelectColor;
@property (nonatomic, strong)NSMutableArray*     noImageArr;
@property (nonatomic, strong)NSMutableArray*    selectImageArr;
@property (nonatomic, strong)NSMutableArray*    btnArr;
@property (nonatomic, strong)UIImageView*    coverImageV;
@property (nonatomic, weak) UIView *smallVideoView;
@property (nonatomic, weak) UIView *toolView;
@property (nonatomic, weak) UIButton *closeBtn;
@property (nonatomic, weak) UIButton *fullBtn;
@property (nonatomic, weak) UIButton *playBtn;
@property (nonatomic, assign, getter=isHideControl) BOOL hideControl;
@property (nonatomic, strong) ZFAVPlayerManager *playerManager;
@property (nonatomic, strong) ZFPlayerController *player;

@end

@implementation ViewController

//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//
//    if (self.smallVideoView && self.smallVideoView.isHidden) {
//        self.smallVideoView.hidden = false;
//    }
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideSmallPlayerNoti:) name:@"hideSmallPlayer" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showSmallPlayerNoti:) name:@"showSmallPlayer" object:nil];
    
    
    self.coverImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.coverImageV.image = [UIImage imageNamed:@"launch_iphone"];
    self.coverImageV.contentMode = UIViewContentModeScaleAspectFit;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.coverImageV];
    
   
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未识别的网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"不可达的网络(未连接)");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [self getData];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [self getData];
                break;
            default:
                break;
        }
    }];
    [manager startMonitoring];
    
    self.SelectColor=[NSMutableArray new];
    self.noImageArr=[NSMutableArray new];
    self.selectImageArr=[NSMutableArray new];
    self.btnArr=[NSMutableArray new];
    self.centView=[[UIView alloc]init];
    
    self.centView.frame=CGRectMake(0,0,SCREEN_WIDTH,GCtabbarHeight);
    [[UITabBar appearance] insertSubview:self.centView atIndex:0];
//    [UITabBar appearance].backgroundColor=[[UIColor whiteColor]colorWithAlphaComponent:0.0f];
    [[UITabBar appearance] setTranslucent:YES];
    self.delegate=self;
    
    FKLastPlayMedia *lastPlayMedia = [FKCacheTool lastPlayVideo];
    if (lastPlayMedia) { // 获取上次播放的视频
        // 上次播放未结束的视频小视窗
        UIView *smallVideoView = [[UIView alloc] init];
        [self.view addSubview:smallVideoView];
        self.smallVideoView = smallVideoView;
        smallVideoView.backgroundColor = [UIColor lightGrayColor];
//        [smallVideoView addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(smallVideoViewDraged:)]];
        CGFloat w = fkScreenW * 0.5;
        CGFloat h = w * 9 / 16.f;
        CGFloat x = fkScreenW - w;
        CGFloat y = fkScreenH - fkOffsetBottom - fkNavBarH - h - 7;
        smallVideoView.frame = CGRectMake(x, y, w, h);
        // 视频容器
        UIView *videoContainer = [[UIView alloc] init];
        [smallVideoView addSubview:videoContainer];
//        [videoContainer addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoContainerDidTap:)]];
        // 按钮容器
        UIView *toolView = [[UIView alloc] init];
        [smallVideoView addSubview:toolView];
        self.toolView = toolView;
        [toolView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toolViewDidTap:)]];
        // 关闭按钮
        UIButton *closeBtn = [UIButton fk_btnWithTarget:self action:@selector(closeBtnClicked) img:[UIImage imageNamed:@"icon_close"]];
        [toolView addSubview:closeBtn];
        self.closeBtn = closeBtn;
//        // 全屏按钮
//        UIButton *fullBtn = [UIButton fk_btnWithTarget:self action:@selector(fullBtnClicked) img:[UIImage imageNamed:@"icon_fullScreen"]];
//        [toolView addSubview:fullBtn];
//        self.fullBtn = fullBtn;
        // 播放、暂停按钮
//        UIButton *playBtn = [UIButton fk_btnWithTarget:self action:@selector(playBtnClicked:) img:[UIImage imageNamed:@"icon_pause"]];
//        [toolView addSubview:playBtn];
//        self.playBtn = playBtn;
//        [playBtn setImage:[UIImage imageNamed:@"icon_playImg"] forState:UIControlStateSelected];
        // 设置约束
        [videoContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        [toolView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(36);
            make.left.offset(4);
            make.top.offset(3);
        }];
//        [fullBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.centerY.equalTo(closeBtn);
//            make.right.offset(-8);
//        }];
//        [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.height.offset(40);
//            make.centerX.centerY.offset(0);
//        }];
        
        
        // 设置播放器
        ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
        self.playerManager = playerManager;
        /// 播放器相关
        self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:videoContainer];
//        self.player.controlView = self.controlView;
        /// 设置退到后台继续播放
        self.player.pauseWhenAppResignActive = NO;
        
        @zf_weakify(self)
        self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.allowOrentitaionRotation = isFullScreen;
        };
        
        // 播放进度发生了改变
        self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
            @strongify(self)
//            self.currentTime = currentTime;
    //        FKLog(@"currentTime: %.2f, duration: %.2f", currentTime, duration);
        };
        
        self.player.playerPlayStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerPlaybackState playState) {
            @strongify(self)
//            if (playState == 2) { // 退出或者暂停的时候记录播放的位置
//                NSMutableDictionary *info = [NSMutableDictionary dictionary];
//                info[@"url"] = asset.assetURL.absoluteString;
//                info[@"currentTime"] = @(self.currentTime);
//                [FKCacheTool saveLastVideoProgress:info];
//            }
        };
        
        /// 播放完成
        self.player.playerDidToEnd = ^(id  _Nonnull asset) {
            @zf_strongify(self)
//            [self.player.currentPlayerManager replay];
//            NSInteger index = [self playNextIndex];
//            
//            if (index < self.playUrls.count) {
//                NSString *url = self.playUrls[index];
//                playerManager.assetURL = [NSURL URLWithString:url];
//                self.selectIndex = index;
//                
//                if (!self.player.isLastAssetURL) {
//                    NSDictionary *dict = self.dataSource[index];
//                    NSString *idStr = dict[@"id"];
//                    [FKCacheTool getMediaDetail:idStr complete:^(id data) {
//                        // 缓存当前播放的媒体信息
//                        [FKCacheTool saveCurrentMedia:data];
//                        
//                        self.currentModel = [ICMusicPlayModel mj_objectWithKeyValues:data];
//                        self.nameLabel.text = self.currentModel.name;
//                        self.desLabel.text = self.currentModel.describe;
//                        [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeLandscape];
//                    }];
//                } else {
//                    [self.player stop];
//                }
//            }
        };
        
        // 设置播放的url
        playerManager.assetURL = [NSURL URLWithString:lastPlayMedia.videoUrl];
        [self.player seekToTime:lastPlayMedia.currentTime.doubleValue completionHandler:^(BOOL finished) {
            @fk_strongify(self)
            [self.playerManager pause];
        }];
    }
    
    
    self.objectAFN=[[ObjectAFNetWorking alloc]init];
    [self getData];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(contentDataUpdate) name:@"contentDataUpdate" object:nil];
}

- (void)hideSmallPlayerNoti:(NSNotification *)noti
{
    if (self.smallVideoView) {
        self.smallVideoView.hidden = true;
        if (self.playerManager.isPlaying) [self.playerManager pause];
    }
}

- (void)showSmallPlayerNoti:(NSNotification *)noti
{
    if (self.smallVideoView) {
        self.smallVideoView.hidden = false;
        if (!self.playerManager.isPlaying) [self.playerManager play];
    }
}



#pragma mark - action
- (void)smallVideoViewDraged:(UIPanGestureRecognizer *)gesture
{
    CGPoint panPoint = [gesture locationInView:self.view];
    
    if(gesture.state == UIGestureRecognizerStateChanged) {
        self.smallVideoView.center = CGPointMake(panPoint.x, panPoint.y);
    } else if(gesture.state == UIGestureRecognizerStateEnded) {
        CGFloat marginX = panPoint.x < fkScreenW * 0.5 ? panPoint.x : fkScreenW - panPoint.x; // 结束拖拽的时候水平方向的最短距离
        CGFloat marginY = panPoint.y < fkScreenH * 0.5 ? panPoint.y : fkScreenH - panPoint.y; // 结束拖拽的时候垂直方向的最短距离
        CGFloat minCenterX = self.smallVideoView.fk_width * 0.5;
        CGFloat maxCenterX = fkScreenW - minCenterX;
        CGFloat minCenterY = self.smallVideoView.fk_height * 0.5 + fkStatusBarH;
//        CGFloat maxCenterY = fkScreenH - minCenterY;
        CGFloat maxCenterY = fkScreenH - fkOffsetBottom - fkTabBarH - self.smallVideoView.fk_height * 0.5;
        CGFloat centerX = panPoint.x;
        if (centerX < minCenterX) {
            centerX = minCenterX;
        } else if (centerX > maxCenterX) {
            centerX = maxCenterX;
        }
        CGFloat centerY = panPoint.y;
        if (centerY < minCenterY) {
            centerY = minCenterY;
        } else if (centerY > maxCenterY) {
            centerY = maxCenterY;
        }
        
        if (marginX < marginY) { // 球即将靠近水平方向的一边
            [UIView animateWithDuration:0.3 animations:^{
                CGFloat ballX = panPoint.x < fkScreenW * 0.5 ? minCenterX : maxCenterX;
                self.smallVideoView.center = CGPointMake(ballX, centerY);
            }];
        } else {  // 球即将靠近竖直方向的一边
            [UIView animateWithDuration:0.3 animations:^{
                CGFloat ballY = panPoint.y < fkScreenH * 0.5 ? minCenterY : maxCenterY;
                self.smallVideoView.center = CGPointMake(centerX, ballY);
            }];
        }
    }
}

//- (void)videoContainerDidTap:(UITapGestureRecognizer *)gesture
//{
//    if (self.toolView.isHidden) {
//        [UIView animateWithDuration:0.25 animations:^{
//            self.toolView.hidden = false;
//        }];
//    }
//}

- (void)toolViewDidTap:(UITapGestureRecognizer *)gesture
{
//    self.hideControl = !self.isHideControl;
//    if (self.isHideControl) {
//        [UIView animateWithDuration:0.25 animations:^{
//            self.closeBtn.hidden = true;
//            self.fullBtn.hidden = true;
//            self.playBtn.hidden = true;
//        }];
//    } else {
//        [UIView animateWithDuration:0.25 animations:^{
//            self.closeBtn.hidden = false;
//            self.fullBtn.hidden = false;
//            self.playBtn.hidden = false;
//        }];
//    }
    
    FKLastPlayMedia *model = [FKCacheTool lastPlayVideo];
    HSVideoPlayViewController *vc = [HSVideoPlayViewController new];
    vc.currentModel = model.media;
    [[UIViewController currentViewController].navigationController pushViewController:vc animated:YES];
    
    [self.playerManager pause];
    self.smallVideoView.hidden = true;
}

- (void)closeBtnClicked
{
    [self.player stop];
    self.player = nil;
    self.playerManager = nil;
    [self.smallVideoView removeFromSuperview];
    
    [FKCacheTool removeLastPlayVideo];
}

- (void)fullBtnClicked
{
    [self.player enterFullScreen:!self.player.isFullScreen animated:YES];
}

- (void)playBtnClicked:(UIButton *)btn
{
    btn.selected = !btn.isSelected;
    if (btn.isSelected) {
        [self.playerManager pause];
    } else {
        [self.playerManager play];
    }
}


- (void)contentDataUpdate{
    [self getData];
}
-(void)getData
{
    ///api/home/AppBottom
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson_tabbar.json"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSData* dataString=[NSData dataWithContentsOfFile:filePath];
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        self.dic=dic;
        [self upDateView];
        [GC_OCTool saveFileAction:filePath];
    }else
    {
        [self.objectAFN getUrlStr:[NSString stringWithFormat:@"%@/api/home/AppBottom",server_addr] finish:^(id  _Nonnull dataString) {
           
            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson_tabbar.json"];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:nil];
            }
            [dataString writeToFile:filePath atomically:YES];
            self.dic=dic;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self upDateView];
            });
        } andError:^(NSError * _Nonnull error) {
        }];
    }
}
-(void)upDateView
{
    [self.coverImageV removeFromSuperview];
    
    if(self.btnArr.count>0){
        return;
    }
    NSMutableArray* navArr=[NSMutableArray new];
    NSArray* array=self.dic[@"data"];
    
    CGFloat btnWdith = SCREEN_WIDTH/array.count;
    CGFloat btnHeight = GCtabbarHeight;
    CGFloat height=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont systemFontOfSize:FontSize(10)] andWidth:wid(100)];
//    NSInteger imageHeight=32;
    CGFloat imgHeight= 28;
    NSMutableArray* imageUrls=[NSMutableArray new];
//    NSLog(@"%@",array);
    for (int i=0;i<array.count;i++){
        
        NSDictionary* dic=array[i];
        [self.SelectColor addObject:[GC_OCTool colorWithHexString:dic[@"color"]]];
        NSString *normalImage = dic[@"image"];
        [self.noImageArr addObject:normalImage];

        [imageUrls addObject:[NSURL URLWithString:normalImage]];

        NSString* str=dic[@"select_image"];
        if(str.length==0){
            str = normalImage;
        }
        [self.selectImageArr addObject:str];
        [imageUrls addObject:[NSURL URLWithString:str]];

        UIViewController* myvc;
        NSInteger type_id = [dic[@"type_id"] integerValue];
        if(type_id == 1){
            
            BOOL exist = NO;
            for (UINavigationController *nav in navArr) {
                if ([nav.viewControllers.firstObject isKindOfClass:[NewHomeViewController class]]) {
                    exist = YES;
                }
            }
            NewHomeViewController* home=[[NewHomeViewController alloc]initWithId:dic[@"media_mediaclass_id"] isHomePage:YES];
            home.titleString = dic[@"name"];
            myvc=home;
        }else if(type_id == 2){
            
            OnlineEducationViewController* online=[[OnlineEducationViewController alloc]init];
            online.idString=dic[@"media_mediaclass_id"];
            myvc=online;
        }else if(type_id == 3){
            BibleViewController* bible=[[BibleViewController alloc]init];
            bible.idString=dic[@"media_mediaclass_id"];
            myvc=bible;
        }
        if ([myvc isKindOfClass:[NewHomeViewController class]]) {
            BaseNavigationController *testnav = [[BaseNavigationController alloc]initWithRootViewController:myvc];
            testnav.tabBarController.tabBar.hidden = YES;
            [navArr addObject:testnav];
        }else {
            FKBaseNavVC *testnav = [[FKBaseNavVC alloc] initWithRootViewController:myvc];
//            UINavigationController *testnav = [[UINavigationController alloc] initWithRootViewController:myvc];
            testnav.tabBarController.tabBar.hidden = YES;
            [navArr addObject:testnav];
        }
        
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(i*btnWdith,0,btnWdith,btnHeight)];
//        CGFloat y = (GCtabbarHeight - HY_BottomWhiteBar_Height - imgHeight - hig(5) -  height);
        CGFloat y = 4;
        UIImageView* imageView=[[UIImageView alloc]initWithFrame:CGRectMake((btnWdith-imgHeight)/2.0,y,imgHeight,imgHeight)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:i==0?dic[@"select_image"]: dic[@"image"]]];
        imageView.tag=200;
        [btn addSubview:imageView];
//        imageView.backgroundColor = UIColor.redColor;

        UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0,y+imgHeight+4,btnWdith,height)];
        label.textColor=i==0?[GC_OCTool colorWithHexString:dic[@"color"]]:[UIColor blackColor];
        label.font=[UIFont systemFontOfSize:FontSize(10)];
        label.textAlignment=NSTextAlignmentCenter;
        label.text=dic[@"name"];
        label.tag=201;
        [btn addSubview:label];
        btn.tag=300+i;
        [self.btnArr addObject:btn];
        [self.centView addSubview:btn];
//        label.backgroundColor = UIColor.greenColor;
        
        self.centView.backgroundColor  = [UIColor whiteColor];
    }
    //预加载图标
    [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:imageUrls];
    self.viewControllers=navArr;
    self.selectedIndex=0;
//    [self btnAction:self.btnArr[0]];
    
    
}

//移除系统tabbar上面的按钮(UITabBarButton类型)
- (void)_removeSystemBarbtn{
    Class class =  NSClassFromString(@"UITabBarButton");
    
    for (UIView *view in self.tabBar.subviews) {
        
        //如果view是由UITabBarButton类创建的对象,则将其移除
        if ([view isKindOfClass:class]) {
            [view removeFromSuperview];
        }
    }
}

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSLog(@"选中===%ld,btn个数====%ld,选中图片===%ld",self.selectedIndex,self.btnArr.count,self.selectImageArr.count);
    for (int i=0;i<self.btnArr.count;i++)
    {
       UIButton*  btn=self.btnArr[i];
        UIImageView* imageView=[btn viewWithTag:200];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.noImageArr[i]]];
        UILabel* label=[btn viewWithTag:201];
        label.textColor=[UIColor blackColor];
    }
    UIButton* sender=self.btnArr[self.selectedIndex];
    UIImageView* imageView=[sender viewWithTag:200];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.selectImageArr[self.selectedIndex]]];
    UILabel* label=[sender viewWithTag:201];
    label.textColor=self.SelectColor[self.selectedIndex];
    
    if ([viewController isKindOfClass:[FKBaseNavVC class]]) {
        FKBaseNavVC *navVC = (FKBaseNavVC *)viewController;
        // 如果当前的控制器不是“怀著”页面
        if (navVC.childViewControllers.count > 0 && ![navVC.childViewControllers.firstObject isKindOfClass:NSClassFromString(@"BibleViewController")]) {
            // 显示视频播放器
            [self showSmallPlayerNoti:nil];
        }
    }
}

@end
